<template>
  <div class="rounded border border-solid border-color-split md:flex md:flex-row md:items-stretch md:h-120">
    <div class="md:w-3/5 flex flex-col">
      <div class="pt-2 px-2 sm:pt-4 sm:px-4 border-0 border-b border-color-split border-solid">
        <div class="pb-2 sm:pb-4">
          <!-- <a-tree-select
            v-model:value="equipmentTypeId"
            size="small"
            :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
            style="width: 200px"
            placeholder="请选择设备类别"
            allow-clear
            tree-default-expand-all
            :tree-data="equipmentTypeList"
            :field-names="{
              label: 'equipmentCategoryName',
              value: isEnterprise ? 'equipmentCategoryId' : 'defaultEquipmentCategoryId',
            }"
            @select="handleSelect"
            @change="handleChange"
          >
          </a-tree-select> -->
          <a-input-search
            v-model:value="keyword"
            :placeholder="placeholder"
            class="ml-4"
            size="small"
            :allow-clear="true"
            :maxlength="32"
            style="width: 200px"
            @search="keywordSearch"
          >
            <template #enterButton>
              <a-button>
                <template #icon><Icon type="icon-sousuo" /></template>
              </a-button>
            </template>
          </a-input-search>
        </div>
      </div>
      <div class="h-full relative rounded overflow-auto">
        <SlTable
          :class="{ 'ant-table-empty-noborder': tableData.length === 0 }"
          :columns="columns"
          :pagination="(false as any)"
          size="small"
          :data-source="tableData"
          :loading="tableLoading"
          :row-key="isEnterprise ? 'equipmentTypeId' : 'defaultEquipmentTypeId'"
          :row-selection="{
            selectedRowKeys: value,
            onSelect,
            getCheckboxProps,
            onSelectAll,
            hideSelectAll: singleSelect,
          }"
          :custom-row="customRow"
          :search-model="searchModel"
          :ignore-keys="['organizationId']"
        >
          <template #bodyCell="{ column, record }: BodyCellOptions<EquipmentTypeItem>">
            <EllipsisText
              v-if="column.dataIndex === 'equipmentTypeName'"
              :max-len="10"
              :text="record.equipmentTypeName"
            />
          </template>
        </SlTable>
      </div>
    </div>
    <div class="md:w-2/5 border-0 border-t md:border-t-0 md:border-l border-solid border-color-split flex flex-col">
      <div class="py-5.5 flex flex-row items-center pl-4 pr-4.5">
        <div class="flex-1">
          <span class="text-lg font-semibold text-color-header">已选</span>
          <span class="text-color-secondary">({{ selectedEquipmentType.length }})</span>
        </div>
        <div class="text-red-400 cursor-pointer" @click="clearSelected"> 清空 </div>
      </div>
      <div v-if="selectedEquipmentType.length > 0" class="flex-1 overflow-auto pl-4 pr-4.5">
        <div
          v-for="(el, i) in selectedEquipmentType"
          :key="el.equipmentTypeId || el.defaultEquipmentTypeId"
          class="flex flex-row items-center mb-4"
        >
          <div class="flex-1 overflow-hidden">
            <span class="text-color-main">{{ el.equipmentTypeName || el.defaultEquipmentTypeName }}</span>
            <!-- <span v-if="hasOrg" class="text-sm text-color-secondary">({{ el.organizations }})</span> -->
          </div>
          <div class="cursor-pointer w-10 text-right">
            <a v-show="!el.equipmentTypeId" @click="removeSelected(el, i)">移除</a>
          </div>
        </div>
      </div>
      <SlEmpty v-else />
    </div>
  </div>
</template>
<script setup lang="ts">
import { useI18n } from "/@/locales/useI18n";
import { nextTick, onMounted, ref, watch, computed, watchEffect } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import SlEmpty from "/@/components/SlEmpty.vue";
import type { EquipmentTypeSelectExpose } from "/@/types/components";
import SlTable from "/@/components/SlTable.vue";
import EllipsisText from "/@/components/common/EllipsisText.vue";
import type { BodyCellOptions } from "/@/types/antd";
import { useUserStore } from "/@/stores/aiot/user";
import { findParents, loopItem } from "/@/utils/treeData";
import { EquipmentCategoryItem } from "/@/api/aiot/equipmentCategory/models";
import type { EquipmentTypeItem } from "/@/api/aiot/equipment/models";
import { pageEquipmentCategorySystem, pageEquipmentCategory } from "/@/api/aiot/equipmentCategory";
import { useEquipmentTypeSelect } from "./useEquipmentTypeSelect";

const props = withDefaults(
  defineProps<{
    //所勾选的用户id数组 双向绑定
    value: string[];
    //不能选择的用户id数组
    // disabledValue?: string[];
    //外面加载过组织数据 这里就不用重复加载了
    // orgData?: OrgUserTreeItem[];
    // orgLoading?: boolean;
    //排除已授权角色用户
    excludeRoleIds?: string;
    singleSelect?: boolean;
    isEnterprise: boolean;
    selectEquipmentTypes?: EquipmentTypeItem[];
    placeholder?: string;
  }>(),
  {
    placeholder: "搜索设备类型",
  }
);
const disabledValue = computed(() => {
  if (props.selectEquipmentTypes && props.selectEquipmentTypes.length > 0) {
    return props.selectEquipmentTypes.map((item) => {
      return item.defaultEquipmentTypeId;
    });
  } else {
    return [];
  }
});
const userStore = useUserStore();
//是否有组织架构数据 默认是, 有的话 则是树组件与table组件共存，没有的话只有table组件
const hasOrg = ref(!userStore.isPlatformUser());
const emits = defineEmits(["update:value", "update:selectEquipmentTypes"]);
const { t } = useI18n();
const equipmentTypeId = ref<string | null>(null);
const equipmentTypeList = ref<EquipmentCategoryItem[]>([]);
// 选择设备类别
const selectEquipmentCateGoryIds = ref<string[]>([]);
function handleSelect(value, node) {
  let data: EquipmentCategoryItem[] = [node];
  selectEquipmentCateGoryIds.value = [];
  loopItem(data, (el, i, item) => {
    if (el.equipmentCategoryId || el.defaultEquipmentCategoryId) {
      selectEquipmentCateGoryIds.value.push(el.equipmentCategoryId || el.defaultEquipmentCategoryId);
    }
  });
}
function handleChange(value) {
  if (!value) {
    selectEquipmentCateGoryIds.value = [];
    reloadTable({ model: { equipmentCategoryIds: [], searchText: keyword.value } });
  }
}
watch(selectEquipmentCateGoryIds, (v) => {
  if (selectEquipmentCateGoryIds.value && selectEquipmentCateGoryIds.value.length > 0) {
    reloadTable({
      model: {
        equipmentCategoryIds: selectEquipmentCateGoryIds.value || [],
        searchText: keyword.value,
      },
    });
  }
});

onMounted(async () => {
  if (props.isEnterprise) {
    equipmentTypeList.value = (await pageEquipmentCategory())?.records || [];
  } else {
    equipmentTypeList.value = (await pageEquipmentCategorySystem())?.records || [];
  }
  reloadTable({
    size: 999,
    current: 1,
    model: { equipmentCategoryIds: selectEquipmentCateGoryIds.value || [], searchText: keyword.value },
  });
});
/**
 * search
 */
const keyword = ref("");
function keywordSearch() {
  reloadTable({
    model: { equipmentCategoryIds: selectEquipmentCateGoryIds.value || [], searchText: keyword.value },
  });
}
/**
 * table
 */

const { Api, columns } = useEquipmentTypeSelect(props.isEnterprise);
const { tableData, tableLoading, pagination, reloadTable, searchModel } = useCURD<EquipmentTypeItem>({
  getPageUrl: Api.equipmentPage,
  loadOnMounted: false,
});
function removeSelected(el: EquipmentTypeItem, i) {
  const copyValue = [...props.value];
  const j = copyValue.indexOf((el.equipmentTypeId || el.defaultEquipmentTypeId) as string);
  if (j >= 0) {
    copyValue.splice(j, 1);
  }
  selectedEquipmentType.value.splice(i, 1);
  const unCheckedKeys = [(el.equipmentTypeId || el.defaultEquipmentTypeId) as string];
  emits("update:value", copyValue);
}
//table select
const selectedEquipmentType = ref<EquipmentTypeItem[]>([]);
// watch(
//   () => props.selectEquipmentTypes,
//   (val) => {
//     console.info("监听传来的默认值==>", val);
//     if (val && val.length > 0) {
//       selectedEquipmentType.value = JSON.parse(JSON.stringify(props.selectEquipmentTypes));
//     }
//   },
//   {
//     deep: true,
//   }
// );
watch(
  selectedEquipmentType,
  (v) => {
    console.info("监听selectedEquipmentType", v);
    emits("update:selectEquipmentTypes", v);
  },
  {
    deep: true,
  }
);
function getCheckboxProps(record: EquipmentTypeItem) {
  // if (disabledValue.value?.includes((record.equipmentTypeId || record.defaultEquipmentTypeId) as string)) {
  //   return { disabled: true };
  // }
}
function onSelectAll(selected: boolean, selectedRows: EquipmentTypeItem[], changeRows: EquipmentTypeItem[]) {
  onUserSelectAll(selected, selectedRows, changeRows, false);
}
function onSelect(record: EquipmentTypeItem, selected: boolean) {
  onUserSelect(record, selected, false);
}
function onUserSelectAll(
  selected: boolean,
  selectedRows: EquipmentTypeItem[],
  changeRows: EquipmentTypeItem[],
  isTree?: boolean
) {
  const copyValue = [...props.value];
  changeRows.forEach((record) => {
    toggleOne(selected, copyValue, record, isTree);
  });
  emits("update:value", copyValue);
}
function onUserSelect(record: EquipmentTypeItem, selected: boolean, isTree?: boolean) {
  const copyValue = [...props.value];
  toggleOne(selected, copyValue, record, isTree);
  emits("update:value", copyValue);
}

function toggleOne(selected: boolean, copyValue: string[], record: EquipmentTypeItem, isTree?: boolean) {
  let index = copyValue.indexOf((record.equipmentTypeId || record.defaultEquipmentTypeId) as string);
  if (selected) {
    if (index === -1) {
      if (props.singleSelect) {
        copyValue[0] = (record.equipmentTypeId || record.defaultEquipmentTypeId) as string;
        selectedEquipmentType.value = [record];
      } else {
        copyValue.push((record.equipmentTypeId || record.defaultEquipmentTypeId) as string);
        selectedEquipmentType.value.push(record);
      }
    }
  } else {
    if (index >= 0) {
      copyValue.splice(index, 1);
      selectedEquipmentType.value.splice(index, 1);
    }
  }
}
function customRow(record: EquipmentTypeItem) {
  return {
    onClick() {
      if (disabledValue.value?.includes((record.equipmentTypeId || record.defaultEquipmentTypeId) as string)) {
        return;
      }
      onSelect(record, !props.value.includes((record.equipmentTypeId || record.defaultEquipmentTypeId) as string));
    },
  };
}
watch(
  () => props.value,
  (v) => {
    if (!v || v.length === 0) {
      selectedEquipmentType.value = [];
    }
  }
);
function clearSelected() {
  let defaultArr = selectedEquipmentType.value.filter((item) => {
    return item.equipmentTypeId;
  });
  let defaultKey =
    defaultArr?.map((item) => {
      return item.defaultEquipmentTypeId;
    }) || [];
  selectedEquipmentType.value = [...defaultArr];
  emits("update:value", defaultKey);
}

/**
 * expose
 */
const myExpose: EquipmentTypeSelectExpose = {
  async reload() {},
  reset() {
    emits("update:value", []);
    keyword.value = "";
    selectEquipmentCateGoryIds.value = [];
    selectedEquipmentType.value = [];
    equipmentTypeId.value = null;
    keywordSearch();
  },
  getSelecedEquipmentType() {
    return selectedEquipmentType.value;
  },
};
defineExpose(myExpose);
</script>
<style lang="less">
.user-depart-tree {
  .ant-tree-checkbox {
    margin: 4px 4px 0;
  }
  .ant-tree-iconEle {
    width: 18px !important;
    margin-right: 5px;
  }
}
</style>
